package com.common.interceptor;

import com.common.enums.ResultEnum;
import com.common.utils.Canca;
import com.common.utils.JwtUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
@ComponentScan
public class CheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod=(HandlerMethod) handler;
            String token = request.getHeader("Authorization");
            if (token.isEmpty()){
                response.sendRedirect(request.getContextPath()+"login");
            }
            try{
                if (token.startsWith("s")){
                    long l = JwtUtils.parserToken(token.substring(1));
                    Canca.setId(l);
                }else {
                    long l = JwtUtils.parserToken(token.substring(1));
                    Canca.setId(l);
                    String token1 = JwtUtils.getToken(Canca.getUserId(), new Date(System.currentTimeMillis() + 2 * 60 * 1000));
                    response.setHeader("St","s"+token1);
                }
            }catch (ExpiredJwtException e){
//                status=201 token有问题
                response.setStatus(201);

                return false;
            }
        }
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("任务完成");
    }
}
